package com.thingple.nfc;

import android.nfc.tech.NfcV;

import com.thingple.util.Strings;

import java.io.IOException;

public class NfcVHandler {

    NfcV card;

    /**
     * ID
     */
    public byte[] id;
    /**
     * UID
     */
    public String uid;

    public byte afi;
    public byte dsfid;

    /**
     * 区块数量
     */
    public byte blockNumber;
    /**
     * 每个区块大小
     */
    public byte blockSize;

    public NfcVHandler(NfcV card) throws IOException {
        this.card = card;
        card.connect();
        init();
    }

    private void init() {

        resolveId();
        try {
            resolveSpec();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void resolveId() {
        id = card.getTag().getId();
        uid = Strings.hex(id);
    }

    private void resolveSpec() throws IOException {
        byte[] cmd = new byte[10];
        cmd[0] = (byte) 0x22; // flag
        cmd[1] = (byte) 0x2B; // command
        System.arraycopy(id, 0, cmd, 2, id.length); // UID
        byte[] spec = card.transceive(cmd);
        blockNumber = spec[12];//可使用的数据块数量，一般为27
        blockSize = spec[13];//每个块byte数组的长度，一般为4
        afi = spec[11];//AFI值在某些领域会需要使用
        dsfid = spec[10];//DSFID值
    }

    public boolean isEnable() {
        if(card ==null){
            //请先连接RFID卡
            return false;
        }
        if(!card.isConnected()){
            //接连中断，请重新连接
            return false;
        }
        return true;
    }
}
